<template>
  <div class="user-info-container">
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
        </div>
      </template>
      
      <div class="avatar-container">
        <div class="avatar-wrapper" @click="showCropper = true">
          <img 
            :src="currentAvatarUrl" 
            class="avatar" 
            alt="用户头像"
          />
          <div class="avatar-hover-mask">
            <el-icon><Camera /></el-icon>
          </div>
        </div>
        <div class="avatar-text">点击更换头像</div>
        <el-button 
          type="primary" 
          size="small" 
          @click="handleUpdateAvatar"
          :disabled="!hasAvatarChanged"
          style="margin-top: 10px;"
        >
          更新头像
        </el-button>
      </div>

      <el-dialog
        v-model="showCropper"
        title="裁剪头像"
        width="600px"
        :close-on-click-modal="false"
      >
        <div class="cropper-container">
          <vue-cropper
            ref="cropperRef"
            :img="cropperImage"
            :autoCrop="true"
            :fixedBox="true"
            :centerBox="true"
            :fixed="true"
            :fixedNumber="[1, 1]"
            :info="true"
            :outputSize="1"
            outputType="png"
            @realTime="cropImage"
          />
        </div>
        <template #footer>
          <div class="cropper-buttons">
            <el-upload
              class="upload-trigger"
              :show-file-list="false"
              :auto-upload="false"
              accept="image/*"
              @change="handleImageSelected"
            >
              <el-button>选择图片</el-button>
            </el-upload>
            <el-button type="primary" @click="confirmCrop">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
        <el-form-item label="登录名称">
          <el-input :model-value="userStore.userInfo?.username" disabled />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="userForm.nickname" />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleUpdateNickname"
            :disabled="!hasNicknameChanged"
          >
            提交修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Camera } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { VueCropper } from 'vue-cropper'
import 'vue-cropper/dist/index.css'
import { updateUserInfo } from '@/api/user'
import { compressImage, validateImage } from '@/utils/imageUtils'

const userStore = useUserStore()
const userFormRef = ref(null)
const avatarUrl = ref('')
const originalAvatarUrl = ref('')
const showCropper = ref(false)
const cropperImage = ref('')
const cropperRef = ref(null)
const croppedImage = ref('')

const userForm = reactive({
  nickname: userStore.userInfo?.nickname || ''
})

const hasNicknameChanged = computed(() => {
  return userForm.nickname !== userStore.userInfo?.nickname
})

const userRules = {
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 2, max: 6, message: '昵称长度在2到6个字符之间', trigger: 'blur' }
  ]
}

const hasAvatarChanged = computed(() => {
  return avatarUrl.value !== originalAvatarUrl.value && avatarUrl.value !== ''
})

const handleImageSelected = (uploadFile) => {
  const file = uploadFile.raw
  if (!validateImage(file)) {
    return
  }
  
  const reader = new FileReader()
  reader.onload = (e) => {
    cropperImage.value = e.target.result
  }
  reader.readAsDataURL(file)
}

// 确认裁剪函数
const confirmCrop = async () => {
  if (cropperRef.value && cropperRef.value.getCropData) {
    try {
      await new Promise((resolve) => {
        cropperRef.value.getCropData(async (data) => {
          // 压缩裁剪后的图片
          const compressedData = await compressImage(data)
          avatarUrl.value = compressedData
          resolve()
        })
      })
      showCropper.value = false
      ElMessage.success('头像已选择，点击更新按钮保存更改')
    } catch (error) {
      ElMessage.error('图片处理失败')
    }
  } else {
    ElMessage.error('请先选择图片')
  }
}

// 实时裁剪函数
const cropImage = (data) => {
  if (data && data.url) {
    croppedImage.value = data.url
  }
}

// 更新头像处理函数
const handleUpdateAvatar = async () => {
  if (avatarUrl.value) {
    try {
      const compressedAvatar = await compressImage(avatarUrl.value)
      const response = await updateUserInfo({
        avatar_type: 'custom',
        avatar_data: compressedAvatar
      })
      
      if (response.code === 200) {
        ElMessage.success('头像更新成功')
        userStore.updateUserInfo({ 
          avatar_type: 'custom',
          avatar_data: compressedAvatar 
        })
        originalAvatarUrl.value = compressedAvatar
      }
    } catch (error) {
      console.error('头像更新错误:', error)
      ElMessage.error('头像更新失败')
    }
  }
}

const handleUpdateNickname = async () => {
  try {
    await userFormRef.value.validate()
    const response = await updateUserInfo({
      nickname: userForm.nickname
    })
    
    if (response.code === 200) {
      ElMessage.success('昵称更新成功')
      userStore.updateUserInfo({ nickname: userForm.nickname })
    }
  } catch (error) {
    ElMessage.error('昵称更新失败')
  }
}

const currentAvatarUrl = computed(() => {
  if (avatarUrl.value) {
    return avatarUrl.value
  }
  return userStore.userInfo?.avatar_data || ''
})

onMounted(() => {
  if (userStore.userInfo?.avatar_data) {
    avatarUrl.value = userStore.userInfo.avatar_data
    originalAvatarUrl.value = userStore.userInfo.avatar_data
  }
})
</script>

<style scoped>
.user-info-container {
  padding: 20px;
}

.info-card {
  max-width: 600px;
  margin: 0 auto;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-wrapper {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  cursor: pointer;
  border: 2px solid #e0e0e0;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-hover-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-hover-mask .el-icon {
  font-size: 24px;
  color: white;
}

.avatar-wrapper:hover .avatar-hover-mask {
  opacity: 1;
}

.avatar-text {
  color: #606266;
  font-size: 14px;
  margin-top: 8px;
}

.cropper-container {
  height: 400px;
  width: 100%;
  overflow: hidden;
}

.cropper-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 10px 0;
}

:deep(.upload-trigger .el-upload) {
  display: block;
}

:deep(.vue-cropper) {
  height: 100%;
  width: 100%;
}

:deep(.cropper-box) {
  height: 100% !important;
}

:deep(.cropper-drag-box) {
  background-color: rgba(0, 0, 0, 0.6);
}

:deep(.cropper-modal) {
  background: rgba(0, 0, 0, 0.6);
}
</style>